﻿using Microsoft.AspNetCore.Mvc;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ_Common;
using System.Text;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RabbitMQ_Consumer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ReceiveController : ControllerBase
    {
        // GET: api/<ReceiveController>
        private readonly ILogger<ReceiveController> _logger;
        public ReceiveController(ILogger<ReceiveController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<string> Get()
        {
            var rounteKey = "test";
            var message = "";
            using (var connection = RabbitMQHelper.GetConnection())
            {
                using (var channel = connection.CreateModel())//创建信道，通信管道
                {
                    //创建队列
                    channel.QueueDeclare(rounteKey, false, false, false, null);
                    //没绑定交换机，但由于rabbitmq有默认交换机
               
                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                      {
                           message = Encoding.UTF8.GetString(ea.Body.ToArray());
                          _logger.LogError($"内容：{Encoding.UTF8.GetString(ea.Body.ToArray())}");
                      };
                    channel.BasicConsume(rounteKey, true, consumer);
                }
            }
            return new string[] { message };
        }



        
    }
}
